package cn.bonoon.kernel.web.controllers;

import javax.servlet.http.HttpServletRequest;

import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.exceptions.PrivilegeException;
import cn.bonoon.kernel.menus.MenuableDefinition;
import cn.bonoon.kernel.menus.ModuleManager;
import cn.bonoon.kernel.menus.privileges.PrivilegeInspector;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.support.services.PrivilegeSupport;
import cn.bonoon.kernel.web.StandardKeyChecker;
import cn.bonoon.kernel.web.models.FrameModel;
import cn.bonoon.kernel.web.models.PanelModel;

public class StandardPanelParser implements PanelParser {

	protected final ModuleManager moduleManager;
	protected final PrivilegeSupport privilegeSupport;
	
	public StandardPanelParser(ModuleManager moduleManager, PrivilegeSupport privilegeSupport) {
		this.moduleManager = moduleManager;
		this.privilegeSupport = privilegeSupport;
	}

	@Override
	public PanelEvent parse(String mid, HttpServletRequest request, LogonUser user) throws Exception{
		FrameModel model = new FrameModel(mid, request);
		MenuableDefinition item = moduleManager.find(model);
		return accessCheck(model, item, user);
	}
	
	/**
	 * <pre>
	 * 子类需要指定界面的框架，可定义为：
	 * 1.layout界面框架，可以使用{@link cn.bonoon.kernel.web.models.LayoutModel LayoutModel}
	 * 2.frame界面框架，可以使用{@link cn.bonoon.kernel.web.models.FrameModel FrameModel}
	 * </pre>
	 */
	protected PanelEvent accessCheck(PanelModel model, MenuableDefinition item, LogonUser user) throws Exception{
		
		PrivilegeInspector privilege = privilegeSupport.privilege(user, item);
		if(!privilege.hasPrivilege(item)){
			throw new PrivilegeException("没有访问[" + item.getName() + "]的权限！");
		}
		
		StandardKeyChecker.setChecker(model, item, user, privilegeSupport);
		
		return new PanelEvent(model, item, user, privilege);
	}
}
